import { Injectable } from '@angular/core';
import {from, Observable} from "rxjs";
import {listen} from "@tauri-apps/api/event";
import {invoke} from "@tauri-apps/api";
import {InvokeArgs} from "@tauri-apps/api/tauri";

@Injectable({
  providedIn: 'root'
})
export class TauriEventService {

  constructor() {

  }

  listen(listenerName: string): Observable<any> {
    return new Observable<any>((subscriber) => {
      // return from(listen(listenerName, v => subscriber.next(v))).subscribe()
      const unlisten = listen(listenerName, v => subscriber.next(v))
      return async () => {
        (await unlisten)()
      }
    });
  }

  sendCommand(cmd: string,  args?: InvokeArgs) {
    return from(
        invoke(cmd, args)
    )
  }
}
